<template>
  <div class="app-container">
    <div class="filter-container">
      编号:
      <el-input
        v-model="search.SearchItem.op_card"
        placeholder="请输入编号"
        class="filter-item search_input"
        @keyup.enter.native="handleFilter"
      />
      姓名:
      <el-input
        v-model="search.SearchItem.RoleName"
        placeholder="请输入姓名"
        class="filter-item search_input"
        @keyup.enter.native="handleFilter"
      />
      手机号:
      <el-input
        v-model="search.SearchItem.op_phone"
        placeholder="请输入手机号"
        class="filter-item search_input"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        @click="deleteFileOrDirectory(sels)"
        :disabled="this.sels.length === 0"
      >
        删除
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="用户搜索加载"
      border
      fit
      highlight-current-row
      @selection-change="selsChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column align="center" label="编号">
        <template slot-scope="scope">
          {{ scope.row.op_card }}
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称">
        <template slot-scope="scope">
          {{ scope.row.op_position_name }}
        </template>
      </el-table-column>
      <el-table-column label="手机号">
        <template slot-scope="scope">
          {{ scope.row.op_phone }}
        </template>
      </el-table-column>
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.op_createtime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.op_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text=""
            inactive-text=""
            :active-value="1"
            :inactive-value="0"
            @change="UpdateState(scope.row.op_card)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <!--修改按钮 -->
        <!-- slot-scope="{ row, $index }"   row代表数据按钮对应的行,  index代表当前行的下标-->
        <template slot-scope="{ row, $index }">
          <!-- @click="handleUpdate(row)  点击按钮执行handleUpdate方法,  row:当前行对应的数据-->
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>

          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="search.page"
      :limit.sync="search.limit"
      @pagination="searchPageList"
    />

    <!--弹出层-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <!--表单定义-->
      <!-- ref="OperatorForm"   表单命名,类似于以前的id
      :rules="rules" 对应的验证规则
      :model="OperatorInfo"   表单绑定的数据模型-->
      <el-form
        ref="OperatorForm"
        :rules="rules"
        :model="OperatorInfo"
        label-position="left"
        :inline="true"
      >
        <!--el-row  代表一行-->
        <el-row>
          <!--:span="12" 代表占一半的地方-->
          <el-col :span="12">
            <!--::rules="this.dialogStatus === '1' ? rules.user_name : []"   表示添加的时候才验证用户名是否已经被占用-->
            <el-form-item
              label="编号"
              prop="op_card"
              :rules="this.dialogStatus === '1' ? rules.op_card : []"
            >
              <!--v-if="this.dialogStatus === '1'"  vue 的if判断  意思 如果是添加,就显示文本-->
              <el-input
                v-if="this.dialogStatus === '1'"
                v-model="OperatorInfo.op_card"
                placeholder="编号一般由MY+6位数组成，如MY000001"
                class="filter-item add_input"
              />
              <!-- v-else  vue 的else  和上面的if判断对应-->
              <el-tag v-else class="filter-item add_input" type="info">{{
                OperatorInfo.op_card
              }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--::rules="this.dialogStatus === '1' ? rules.user_name : []"   表示添加的时候才验证用户名是否已经被占用-->
            <el-form-item
              label="账号"
              prop="op_account"
              :rules="this.dialogStatus === '1' ? rules.op_account : []"
            >
              <!--v-if="this.dialogStatus === '1'"  vue 的if判断  意思 如果是添加,就显示文本-->
              <el-input
                v-if="this.dialogStatus === '1'"
                v-model="OperatorInfo.op_account"
                placeholder="请输入登录用账号"
                class="filter-item add_input"
              />
              <!-- v-else  vue 的else  和上面的if判断对应-->
              <el-tag v-else class="filter-item add_input" type="info">{{
                OperatorInfo.op_account
              }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'公司名称'" prop="op_position_name">
              <el-input
                v-model="OperatorInfo.op_position_name"
                class="filter-item add_input"
                placeholder="请输入所在公司名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="op_id">
              <el-select
                v-model="OperatorInfo.op_id"
                placeholder="请选择操作员姓名"
                value-key="op_id"
              >
                <el-option
                  v-for="item in employeeSelectOptions"
                  :key="item.emp_id"
                  :label="item.emp_name"
                  :value="item.emp_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--v-model="OperatorInfo.roleList"  直接绑定OperatorInfo  里面的角色列表 
            :remote-method="roleSearch"  输入文本执行搜索的方法 
            value-key="op_role"  因为v-model绑定是对象, 这里需要配置绑定的主键是哪个字段 -->
            <el-form-item label="分配角色" prop="op_role">
              <el-select
                v-model="OperatorInfo.op_role"
                placeholder="请选择对应的角色"
                value-key="op_role"
              >
                <el-option
                  v-for="item in userRoleSelectOptions"
                  :key="item.role_id"
                  :label="item.role_name"
                  :value="item.role_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="this.dialogStatus === '1'">
          <el-col :span="12">
            <!--\u3000代表大空格 -->
            <el-form-item :label="'输入密码'" prop="op_pwd">
              <el-input
                v-model="OperatorInfo.op_pwd"
                type="password"
                placeholder="请输入登录密码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="vpass_word">
              <el-input
                v-model="OperatorInfo.vpass_word"
                type="password"
                placeholder="请再次输入登录密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- dialogStatus === '1' 是添加 就执行添加的方法  是修改  就执行修改的方法-->
        <el-button
          type="primary"
          @click="dialogStatus === '1' ? addOperator() : updateData()"
        >
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
//引用
import {
  getOperatorPage,
  validateAccount,
  validateCard,
  OperatorAdd,
  GetOperatorByCard,
  UptOperator,
  DelOperator,
  GetRoles,
  GetEmployees,
  UptStateByCard,
  DelOperatorList,
} from "@/api/OperatorManage/OperatorManage_index"; // 引入操作api
import Pagination from "@/components/Pagination"; // 引入分页
import { getToken } from "@/utils/auth"; // 引入提取token的方法

export default {
  name: "OperatorManager",
  components: { Pagination },
  data() {
    // 验证密码
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.OperatorInfo.vpass_word !== "") {
          this.$refs.OperatorForm.validateField("vpass_word");
        }
        callback();
      }
    };
    // 验证验证密码
    var validateVPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.OperatorInfo.op_pwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    // 验证输入账号是否有效(是否在数据库中存在)
    var op_account = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        validateAccount(value).then((response) => {
          console.log("response.data" + response.data);
          if (response.data) {
            callback();
          } else {
            callback(new Error("输入账号已经被占用"));
          }
        });
      }
    };
    // 验证输入编号是否有效(是否在数据库中存在)
    var op_card = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入编号"));
      } else {
        validateCard(value).then((response) => {
          console.log("response.data" + response.data);
          if (response.data) {
            callback();
          } else {
            callback(new Error("输入编号已经被占用"));
          }
        });
      }
    };
    return {
      list: null,
      listLoading: true,
      total: 0,
      search: {
        page: 1,
        limit: 10,
        OrderBy: "op_card",
        SearchItem: {},
      },
      dialogFormVisible: false, // 是否显示弹出层
      dialogTitle: "", // 弹出层标题
      dialogStatus: "1", // 等于1 表示是添加操作   不等于1 表示修改操作
      userRoleSelectOptions: [],
      employeeSelectOptions: [],
      sels: [], //选中的值显示
      //downloadLoading: false, // 导出按钮加载
      OperatorInfo: {
        op_account: "",
        op_pwd: "",
        vpass_word: "",
        op_card: "",
        op_id: "",
        departmentId: 1,
        op_state: 1,
        RoleName: "",
        op_role: "",
        op_phone: "",
        userName: "",
        op_position_name: "",
        op_createtime: new Date(),
      },
      rules: {
        // 验证配置
        // 验证
        op_account: [
          { required: true, message: "账号必须输入", trigger: "change" }, // 验证是否为空
          { validator: op_account, trigger: "blur" }, // 自定义验证, 验证用户名是否存在
        ],
        op_card: [
          { required: true, message: "编号必须输入", trigger: "change" }, // 验证是否为空
          { validator: op_card, trigger: "blur" }, // 自定义验证, 验证用户名是否存在
        ],
        // user_full_name: [
        //   { required: true, message: "姓名必须输入", trigger: "change" },
        // ],
        op_pwd: [
          { required: true, message: "密码必须输入", trigger: "change" },
          { validator: validatePass, trigger: "blur" },
        ],
        vpass_word: [
          { required: true, message: "验证密码必须输入", trigger: "change" },
          { validator: validateVPass, trigger: "blur" },
        ],
        // roleSelectValue: [
        //   { required: true, message: "必须选择用户角色", trigger: "change" },
        // ],
      },
    };
  },
  created() {
    this.searchPageList();
    this.roleSearch();
    this.employeeSearch();
  },
  methods: {
    searchPageList() {
      // 搜索方法
      this.listLoading = true; // 显示加载效果
      getOperatorPage(this.search).then((response) => {
        // 调用分页接口
        this.list = response.data.data; // 将查询结果赋值给list
        this.listLoading = false; // 隐藏加载效果
        this.total = response.data.recordsTotal; // 赋值总行数
      });
    },
    handleFilter() {
      // 点击搜索
      this.search.page = 1; // 将当前页设置为第一页
      this.searchPageList(); // 调用搜索分页方法
    },
    roleSearch() {
      GetRoles().then((response) => {
        if (response.code === 20000) {
          this.userRoleSelectOptions = response.data;
        }
      });
    },
    employeeSearch() {
      GetEmployees().then((response) => {
        if (response.code === 20000) {
          this.employeeSelectOptions = response.data;
        }
      });
    },
    resetOperator() {
      // 初始化用户对象
      this.OperatorInfo = {
        op_account: "",
        op_pwd: "",
        vpass_word: "",
        op_card: "",
        op_id: "",
        departmentId: 1,
        op_state: 1,
        RoleName: "",
        op_role: "",
        op_phone: "",
        userName: "",
        op_createtime: new Date(),
      };
    },
    handleCreate() {
      // 弹出添加页面
      this.resetOperator();
      this.dialogStatus = "1"; // 等于1 表示是添加操作   不等于1 表示修改操作
      this.dialogTitle = "添加";
      this.dialogFormVisible = true; // 当等于true  弹出层显示
      this.$nextTick(() => {
        this.$refs["OperatorForm"].clearValidate(); // 清理验证
      });
    },
    addOperator() {
      // 添加操作员方法
      this.$refs["OperatorForm"].validate((valid) => {
        if (valid) {
          OperatorAdd(this.OperatorInfo).then((response) => {
            this.dialogFormVisible = false;
            this.searchPageList();
            this.$notify({
              title: "添加成功",
              message: "添加操作员成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      // 修改弹出层
      GetOperatorByCard(row.op_card).then((r) => {
        if (r.code === 20000) {
          this.OperatorInfo = r.data; // 返回数据 赋值给OperatorInfo

          this.dialogStatus = "2"; // 代表是修改
          this.dialogFormVisible = true; // 显示弹出层
          this.$nextTick(() => {
            this.$refs["OperatorForm"].clearValidate();
          });
          this.$forceUpdate(); // 渲染
        }
      });
      // copy obj
    },
    UpdateState(card) {
      UptStateByCard(card).then((r) => {
          if (r.code === 20000) {
            this.searchPageList();
          } else {
            this.$message.error(r.mess);
          }
        });
    },
    updateData() {
      this.$refs["OperatorForm"].validate((valid) => {
        if (valid) {
          UptOperator(this.OperatorInfo).then((response) => {
            this.dialogFormVisible = false;
            this.searchPageList();
            this.$notify({
              title: "修改成功",
              message: "修改操作员成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$confirm("此操作将永久删除操作员 , 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        DelOperator(row.op_card).then((r) => {
          if (r.code === 20000) {
            this.searchPageList();
          } else {
            this.$message.error(r.mess);
          }
        });
      });
    },
    selsChange(sels) {
      this.sels = sels;
    },
    deleteFileOrDirectory() {
      var keys = this.sels.map((item) => item.op_card).join(); //获取所有选中行的Key组成的字符串，以逗号分隔
      console.log(keys);
      this.$confirm("此操作将永久删除操作员 , 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        DelOperatorList(keys).then((r) => {
          if (r.code === 20000) {
            this.searchPageList();
          } else {
            this.$message.error(r.mess);
          }
        });
      });
    },
  },
};
</script>
<style>
.search_input {
  width: 200px;
}
.add_input {
  width: 400px;
}
</style>